package com.example.myapplication02;

import android.os.Bundle;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapplication02.databinding.ActivityMainBinding;
import com.example.myapplication02.paging.MyPagedAdapter;
import com.example.myapplication02.paging.room.User;
import com.example.myapplication02.paging.room.UserDao;
import com.example.myapplication02.paging.room.UserDatabase;

import java.util.concurrent.CompletableFuture;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    private UserDao dao;
    private MyPagedAdapter adapter;
    private LiveData<PagedList<User>> liveData;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        dao = UserDatabase.getInstance(this).getUserDao();
        adapter = new MyPagedAdapter();
        binding.rv.setAdapter(adapter);
        binding.rv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        liveData = new LivePagedListBuilder<>(dao.getAllUser(), 5).build();
        liveData.observe(this, users -> adapter.submitList(users));

        binding.btnClear.setOnClickListener(v -> CompletableFuture.runAsync(() -> dao.deleteAllUser()));
        binding.btnPopulate.setOnClickListener(v -> CompletableFuture.runAsync(() -> dao.insert(new User("User" + (int) (Math.random() * 100)))));

    }
}